package com.chen.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.chen.common.MyExpection;
import com.chen.common.Result;

import com.chen.pojo.EmpDO;
import com.chen.service.IEmpService;
import com.chen.service.ILoginService;
import com.chen.utils.JwtUtil;
import com.chen.vo.login.LoginReqVO;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Map;

import static com.chen.constants.ErrorCodeConstants.LOGIN_PASSWORD_ERROR;
import static com.chen.constants.ErrorCodeConstants.LOGIN_USERNAME_NOT_EXIST;

/**
 * ClassName: LoginServiceImpl
 * Package: com.chen.service.impl
 * Description:
 *
 * @Author 陈俊辉
 * @Create 2024/4/12 2:41
 * @Version 1.0
 */
@Service
public class LoginServiceImpl implements ILoginService {
    @Resource
    public IEmpService empService;

    /**
     * 登录验证
     * @param reqVO
     * @param response
     * @return
     */
    @Override
    public Result login(LoginReqVO reqVO, HttpServletResponse response) throws MyExpection {
        //获取用户名和密码
        String username = reqVO.getUsername();
        String password = reqVO.getPassword();
        //验证
        doLogin(username, password);
        //返回jwt令牌
       Map<String, Object> claims = new HashMap<>();
       claims.put("username",username);
       claims.put("password",password);
        String token = JwtUtil.generateJwt(claims);
        //设置响应体

        return Result.success(token);
    }
    @Override
    @SneakyThrows
    public void doLogin(String username,String password){
        //验证
        EmpDO empDO=empService.getEmpByUserName(username);
        if(ObjectUtil.isNull(empDO)){
            throw new MyExpection(LOGIN_USERNAME_NOT_EXIST);
        }
        if(!StrUtil.equals(password,empDO.getPassword())){
            throw new MyExpection(LOGIN_PASSWORD_ERROR);
        }
    }
}
